package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.fb.MyPushIntentService;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.AgentReCommendAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AgentRecommand;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.utility.StepRecord;
import com.gongpingjialoan.widget.LoadingDialog;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;

import org.json.JSONObject;

/**
 * 经纪人推荐车
 * Created by chuang on 2016/10/27.
 */
public class AgentReCommendCarActivity extends BaseActivity implements NetDataJson.OnStringListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ExpandableListView>, PullToRefreshBase.OnLastItemVisibleListener {

    public static final int UNLIKE = 1001;

    private static final int LOGINING_FORSEECAR = 4;

    private PullToRefreshExpandableListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ExpandableListView listView;

    private View footView;

    private AgentRecommand mAgentRecommand = new AgentRecommand();

    private NetDataJson mNetDataJson;

    private NetDataJson mCancelMeetNetDataJson;

    private AgentReCommendAdapter mAgentReCommendAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private LoadingDialog loadingDialog;

    private String fromType;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UNLIKE:
                    String id = msg.obj.toString();
                    cancelMeet(id);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        action = "my_appointRecord";
        isSendData = true;
        isScrollPage = true;
        action = "my_dealerRecommendList";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.meet_record_layout);
        setTitle("经纪人推荐车");
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshExpandableListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        mAgentReCommendAdapter = new AgentReCommendAdapter(mAgentRecommand, this, mHandler);

        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mAgentReCommendAdapter);
        listView.removeFooterView(footView);
        listView.setClipToPadding(false);
        listView.setGroupIndicator(null);
        listView.setChildDivider(getResources().getDrawable(R.color.white));
        listView.setDividerHeight(DhUtil.dip2px(this, 5));

        //不能点击收缩：
        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;
            }
        });

        mNetDataJson = new NetDataJson(this, 1);

        loadingDialog = new LoadingDialog(this);

        fromType = getIntent().getStringExtra("type");
        String job_id = getIntent().getStringExtra("job_id");
        String source = getIntent().getStringExtra("source");
        if (MyPushIntentService.RECOMENDCARLIST.equals(fromType)) {
            StepRecord.recordStep(this, "pushnotification", "{type:" + fromType + ",source:" + source + ",job_id:" + job_id + "}");
        }


        getDataFromNet();
    }


    private void getDataFromNet() {
        if (GPJApplication.getInstance().isLogin()) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    pullToRefreshListView.setRefreshing();
                }
            }, 300);
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, LOGINING_FORSEECAR);
        }
    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.setUrl(API.get_recommend_car_list);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            // Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(String json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (isRefresh) {
            mAgentReCommendAdapter.clear();
        }
        Gson gson = new Gson();
        mAgentRecommand = gson.fromJson(json, AgentRecommand.class);
        if (mAgentRecommand.getData() == null || 0 == mAgentRecommand.getData().getRecords().size()) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        int page_num = mAgentRecommand.getData().getPage_num();
        if (page_num <= mPage) {
            mHasMore = false;
        }

        mAgentReCommendAdapter.setData(mAgentRecommand);
        for (int i = 0; i < mAgentReCommendAdapter.getGroupCount(); i++) {
            listView.expandGroup(i);
        }
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (mCancelMeetNetDataJson != null) {
            mCancelMeetNetDataJson.cancelTask();
            mCancelMeetNetDataJson = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }


    private void cancelMeet(String id) {
        loadingDialog.show();
        mCancelMeetNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                loadingDialog.dismiss();
                Toast.makeText(AgentReCommendCarActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                Toast.makeText(AgentReCommendCarActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                refresh();
            }
        });

        mCancelMeetNetDataJson.cancelTask();
        mCancelMeetNetDataJson.addParam("id", id);
        mCancelMeetNetDataJson.setUrl(API.post_dislike_dealer_recommend);
        mCancelMeetNetDataJson.request("post");
    }

    @Override
    public void onBackPressed() {
        //表示从推送而来
        if (MyPushIntentService.RECOMENDCARLIST.equals(fromType)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOGINING_FORSEECAR) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pullToRefreshListView.setRefreshing();
                    }
                }, 300);
            }
        } else {
            if (requestCode == LOGINING_FORSEECAR) {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }
    }

}
